#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import os
import web
import json
import traceback
import urllib

from Umpweb.base import render_jinja
from Umpweb.db import api as db_api
from Umpweb.common import utils, config
from Umpweb.common.utils import login_required
from Umpweb.base import session, _, render_jinja

urls = (
    '/list', 'FolderList',
    '/grid', 'GridFolder',
    '/create', 'FolderCreate',
    '/delete', 'FolderDelete',
    '/update', 'FolderUpdate',

)

app = web.application(urls, locals())
render = render_jinja('static/templates/folder', encoding='utf-8', )


class FolderList:
    @login_required
    def GET(self):
        web.header("Content-Type", "text/plain")
        return render.folder_list()


class GridFolder:
    @login_required
    def GET(self):
        web_input = web.input()

        filters = {}

        page, total, records, rows = \
            utils.grid_rows_query(db_api.folder_table, web_input, filters=filters)

        cells = ['id', 'name', 'status', 'ec_show','username', 'created_at']
        rows_json = utils.grid_json(page, total, records, rows, 'id', cells)

        web.header("Content-Type", "application/json")
        return rows_json


class FolderCreate:
    def GET(self):
        access_policy = db_api.access_control_get_all()
        return render.folder_create(access_policy=access_policy)

    def POST(self):
        values = dict(**web.input())
        print values
        web.header("Content-Type", "application/json")
        body = {"FolderCreate": {'params': values}}
        return utils.web_return(body)


class FolderUpdate:
    def GET(self):
        x = web.input()
        folder_id = x['folder_id']
        folder = db_api.folder_get(folder_id)
        access_policy = db_api.access_control_get_all()
        print folder.ec_data
        return render.folder_update(folder=folder, access_policy=access_policy)

    def POST(self):
        values = dict(**web.input())
        web.header("Content-Type", "application/json")

        body = {"FolderUpdate": {'params': values}}
        return utils.web_return(body)


class FolderDelete:
    @login_required
    def POST(self):
        web.header("Content-Type", "application/json")
        values = dict(**web.input())
        body = {"FolderDelete": {'params': values}}
        return utils.web_return(body)
